<script setup>
import { PlusOutlined, EllipsisOutlined } from "@ant-design/icons-vue";
import { ref, watch, reactive, onMounted, computed, onUnmounted } from "vue";
import request from "@/common/utils/request";
import { Empty, message } from "ant-design-vue";
import { useRoute, useRouter } from "vue-router";

import  utils from '@/common/utils/utils.js'

// 卡片组件
import AIdigitalHumanCartItem from "./Components/AIdigitalHumanCartItem/index.vue";

// 创建数字人弹窗
import CreatAIdigitalHuman from "./Components/CreatAIdigitalHuman/index.vue";
const CreatAIdigitalHumanRef = ref(null);

const spinning = ref(false);

const state = reactive({
  // 历史记录 分页数据
  log_serchData: {
    total: 0,
    page: 1,
    pageSize: 10
  },
  serchData: {},
  // 状态 options
  statusArr: [],
  time: [],
  // 头部筛选框
  serchValue: {
    // 数字人名称
    name: '',
    // 状态筛选 
    status: null,
    start_time: '',
    end_time: ''
  }
});

const route = useRoute();
const router = useRouter();

// 判断是否没有登录
const notLogin = (type) => {
  const not = !utils.isLogin()
  if(not) message.warning('请先登录!')
  return not
}

// 打开数字人弹窗
const creatSelfAiHuman = () => {
  if(notLogin('creatSelfAiHuman')) return
  CreatAIdigitalHumanRef.value.showModal();
};

const submitChange = () => {
  CreatAIdigitalHumanRef.value.closeModal();
  getHumanRecord();
};

const humanRecordList = ref([]);
const simpleImage = ref(Empty.PRESENTED_IMAGE_SIMPLE);

// 训练记录分页change
const logPaginationChange = () => {
  getHumanRecord()
}

// 重置搜索状态
const resetSerch = () => {
  if(notLogin('resetSerch')) return
  state.log_serchData = {
    total: 0,
    page: 1,
    pageSize: 10
  }
  state.serchValue = {
    // 数字人名称
    name: '',
    // 状态筛选 默认全部
    status: 'all',
    start_time: '',
    end_time: ''
  }
  state.time = []
  getHumanRecord()
}

const timeChange = (value, model) => {
  console.log(model, "时间变化");
  state.serchValue.start_time = model[0];
  state.serchValue.end_time = model[1];
  // // 日期被设为空值, 重新获取列表数据
  getHumanRecord();
};


const timerId = ref(null)

// 获取所有数字人列表
const getHumanRecord = (data = { polling:false}) => {
  if(notLogin('getHumanRecord')) return
  if (timerId.value) {
    clearInterval(timerId.value)
    timerId.value = null
  }
  if (!data.polling) {
    spinning.value = true;
  }
  const params = {
    ...state.log_serchData,
    ...state.serchValue,
    status: state.serchValue.status == 'all'
      ? ''
      : state.serchValue.status
  }
  // /digital/human/record
  request
    .get("/work_ai", "/digital/human/list", params)
    .then((res) => {
      console.log(res, '列表数据');

      humanRecordList.value = res.result.data;
      state.log_serchData.total = res.result.total;
      spinning.value = false;

      const isPolling = res.result.data.some(item => item.status != 3 && item.status != 4)
      if (isPolling) {
        timerId.value = setTimeout(() => {
          getHumanRecord({polling:true})
        }, 2000)
      }
    })
    .catch((err) => {
      spinning.value = false;
    });
};
const getStates = async () => {  
  if(notLogin('getStates')) return

  const res = await request
    .get("/work_ai", "/digital/human/required/information")
  console.log(res, '筛选字段');
  state.serchData = res.result

  console.log(state.serchData, 'state.serchData');
  res.result.humanStatus.select.unshift({
    label: '全部状态',
    value: 'all'
  })
  state.statusArr = res.result.humanStatus.select
  // 默认选中全部状态
  state.serchValue.status = 'all'
}
const init = () => {
  if(!utils.isLogin()) return
  getHumanRecord();
  getStates()
};
init();

const delItem = async (id) => {
  try {
    const res = await request
      .del("/work_ai", "/digital/human/delete", {
        id
      })
    if (res?.code && res.code != 1000) throw new Error(res.msg)
    message.success('删除成功')
    // 删除后判断是否需要往前翻页
    if (humanRecordList.value.length === 1 && state.log_serchData.page > 1) {
      state.log_serchData.page--;
    }
    getHumanRecord()

  } catch (error) {
    message.error(error.message || '删除失败')
  }
}

onMounted(() => {
  if (route.query?.type) {
    creatSelfAiHuman();
  }
});

onUnmounted(() => {
  // 离开摧毁定时器
  if (timerId.value) {
    clearInterval(timerId.value)
    timerId.value = null
  }
})
</script>

<template>
  <div class="digitalHumanComponents">
    <a-spin tip="加载中..." :spinning="spinning">
      <!-- 模板广场头部 start -->
      <div class="smart-clip-header">
        <div class="smart-clip-header-title_top">定制你的专属数字人</div>
        <div class="smart-clip-header-desc">
          通过上传一段您的30s~300s
          视频，1~3分钟轻松复刻专属您的数字人分身
        </div>
      </div>
      <div class="AIdigitalHuman_content">
        <!-- 创建的卡片 -->
        <!-- <div class="top_creat_content" v-if="false">
          <div class="cart_creat" @click="creatSelfAiHuman">
            <PlusOutlined class="add_icon"></PlusOutlined>
            <span>请上传一段视频</span>
            <span>快速复刻自己的数字人分身</span>
          </div>
          <div class="top_creat_box">
            <AIdigitalHumanCartItem @changeName="(e) => (isItem.name = e)" v-for="item in humanListFilters"
              :key="item.id" :item="item" ref="AIdigitalHumanCartItemRef"></AIdigitalHumanCartItem>
          </div>
          <a-pagination style="margin-top: 10px;" :showSizeChanger="true" :hideOnSinglePage="true"
            @change="logPaginationChange" v-model:current="state.loding_serchData.page"
            v-model:pageSize="state.loding_serchData.pageSize" :total="state.loding_serchData.total" />
        </div> -->
        <!-- <a-divider /> -->
        <!-- 头部的搜索栏 -->
        <div class="serch_title">
          <div class="serch_left">
            <div class="serch_item">
              <a-input allow-clear @change="(e) => e.type == 'click' && getHumanRecord()" style="width: 229px"
                v-model:value="state.serchValue.name" placeholder="请输入任务名称">
                <template #prefix>
                  <SearchOutlined />
                </template>
              </a-input>
            </div>

            <div class="serch_item">
              <a-select :field-names="{ label: 'label', value: 'value', options: 'children' }" style="width: 200px"
                v-model:value="state.serchValue.status" :filter-option="false" @change="getHumanRecord"
                :placeholder="'请选择筛选状态'" :options="state.statusArr">
              </a-select>
            </div>

            <div class="serch_item">
              <!-- 日期  -->
              <a-range-picker @change="timeChange" format="YYYY-MM-DD" style="width: 229px" v-model:value="state.time"
                show-time />
            </div>
            <a-button type="primary" :loading="state.serchLoding" @click="getHumanRecord">查询</a-button>
            <a-button :loading="state.serchLoding" @click="resetSerch">重置</a-button>
          </div>
        </div>
        <div class="bottom_history_box">
          <h2>训练记录</h2>
          <!-- v-if="humanRecordList.length" -->
          <div class="cart_box" >
            <div class="cart_creat" @click="creatSelfAiHuman">
              <PlusOutlined class="add_icon"></PlusOutlined>
              <span>请上传一段视频</span>
              <span>快速复刻自己的数字人分身</span>
            </div>
            <AIdigitalHumanCartItem v-if="humanRecordList.length" @delItem="delItem" v-for="item in humanRecordList" :key="item.id" :item="item"
              ref="AIdigitalHumanCartItemRef">
            </AIdigitalHumanCartItem>

            <div v-else class="empty_box">
              <a-empty  :image="simpleImage" />
            </div>

          </div>
       
          <!-- 训练记录 分页 -->
          <a-pagination style="margin-top: 20px;" :showSizeChanger="true" :hideOnSinglePage="true"
            @change="logPaginationChange" v-model:current="state.log_serchData.page"
            v-model:pageSize="state.log_serchData.pageSize" :total="state.log_serchData.total" />
        </div>
      </div>
    </a-spin>
  </div>

  <!-- 创建数字人弹窗 -->
  <CreatAIdigitalHuman ref="CreatAIdigitalHumanRef" @submit="submitChange"></CreatAIdigitalHuman>
</template>

<style lang="less" scoped>
@fs_color: rgba(112, 112, 112, 1);

.digitalHumanComponents {
  padding: 10px;

  .AIdigitalHuman_content {
    background: #fff;
    padding: 12px 0;
    display: flex;
    flex-direction: column;
    padding: 20px;
    // overflow: hidden;
    margin-top: 20px;

    // table 头部的筛选
    .serch_title {
      display: flex;
      align-items: center;
      justify-content: space-between;
      gap: 20px;
      // margin-top: 10px;
      margin-bottom: 20px;

      .serch_left {
        display: flex;
        gap: 0 10px;

        .serch_item {
          display: flex;
          justify-content: center;
          align-items: center;

          .left_prefix {
            padding: 0 25px;
            background-color: #ffffff;
            line-height: 30px;
            border: 1px solid #d9d9d9;
            border-right: none;
          }
        }
      }
    }

    // 无用
    .top_creat_content {
      // display: flex;



      // 编辑的每一项
      .top_creat_box {
        // margin-bottom: 20px;
        display: flex;
        gap: 20px;
        width: 100%;
        overflow-x: auto;
        padding-bottom: 20px;

        &::-webkit-scrollbar {
          width: 8px;
          /* 滚动条的宽度 */
          height: 8px;
          /* 滚动条的高度，垂直滚动条可能用得上 */
        }

        &::-webkit-scrollbar-thumb {
          background: #888;
          /* 滑块的背景颜色 */
          border-radius: 10px;
          /* 滑块的圆角 */
        }
      }
    }

    // 底部生成记录
    .bottom_history_box {

      // 卡片样式提取到外层
      .cart_creat {
        height: 300px;
        // margin-right: 20px;
        width: 210px;
        min-width: 210px;
        // max-width: 190px;
        background-color: #f7f7f5;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        font-size: 13px;
        color: @fs_color;
        border: 1px dashed #a5a5a5;
        border-radius: 10px;
        gap: 5px;
        overflow: hidden;

        transition: all 0.3s;
        cursor: pointer;

        &:hover {
          border-color: var(--ss-primary-color-active);
        }

        .add_icon {
          font-size: 26px;
        }
      }
      h2 {
        font-size: 16px;
        font-weight: 600;
        margin-bottom: 20px;
      }

      .cart_box {
        display: flex;
        gap: 20px;
        flex-wrap: wrap;
        align-content: flex-start;
        // justify-content: space-evenly;
      }
    }
  }

  // 头部
  .smart-clip-header {
    padding: 30px;
    border-radius: 12px;
    // height: 180px;
    min-width: 1140px;
    // margin-top: 20px;
    background: linear-gradient(220deg, #f3f7ff, rgba(159, 191, 255, 0.4));
    display: flex;
    flex-direction: column;

    .smart-clip-header-title_top {
      font-size: 24px;
      color: #0c0d0e;
      line-height: 1.5;
    }

    .smart-clip-header-desc {
      font-size: 14px;
      color: #737a87;
      margin-top: 5px;
      line-height: 1.5;
    }

    .smart-clip-header-btngroup {
      margin-top: 15px;
    }
  }
}



.empty_box{
  width: calc(100% - 400px);
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
